package com.gitee_sunstar.idfa_helper

import android.content.Context
import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar

/** IdfaHelperPlugin */
class IdfaHelperPlugin : FlutterPlugin, MethodCallHandler, IdfaHelper.IdfaHelperListener() {
    private lateinit var channel: MethodChannel
    private lateinit var context: Context
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        context = flutterPluginBinding.applicationContext
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "idfa_helper")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "initAndroid" -> {
                IdfaHelper.instance.bindListener(this)
                result.success(true)
            }
            "startGetId" -> {
                val arguments = call.arguments as Map<*, *>
                val certFilePath = arguments["certFilePath"] as String
                        ?: "";
                val openLog = arguments["openLog"] as Boolean
                        ?: false;
                IdfaHelper.instance.initIdfaHelper(context, certFilePath, openLog)
                result.success(true)
            }
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onIdsValid(id: String) {
        channel.invokeMethod("onIdfaValid", id)
    }

    override fun error(msg: String) {
        channel.invokeMethod("error", msg)
    }
}
